package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FilePermission;
import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    public AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file/*名字不要写错了，要和前端保持一致*/) {
        log.info("文件上传...");

        try {
            //截取原始文件名的拓展名
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf('.'));
            //用uuid雪花id+原始文件名拓展名 生成新的文件名
            String filename = UUID.randomUUID().toString() + substring;
            //返回上传后文件的访问路径,回显回去.我们只需要回显url,回显的逻辑由前端处理
            String filepath = aliOssUtil.upload(file.getBytes(), filename);//上传的文件，上传到阿里云oss处文件的命名
            return Result.success(filepath);
        } catch (IOException e) {
            log.error("文件上传失败...{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
